package com.makemoney.miniprogram.modules.users.rest;

import com.makemoney.miniprogram.common.consts.Constant;
import com.makemoney.miniprogram.common.result.CommonResult;
import com.makemoney.miniprogram.modules.users.dto.IMyUserDetails;
import com.makemoney.miniprogram.modules.users.dto.LoginDTO;
import com.makemoney.miniprogram.modules.users.dto.MyUserDetails;
import com.makemoney.miniprogram.modules.users.dto.TokenDTO;
import com.makemoney.miniprogram.modules.users.service.IAuthorizeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/authorize")
@Tag(name = "授权")
public class AuthorizeController {

    @Resource
    private IAuthorizeService authorizeService;

    @Operation(summary = "登录", description = "用于用户登录，通过提交用户名和密码来获取授权令牌。")
    @PostMapping("/login")
    public CommonResult<TokenDTO> login(@Valid @RequestBody LoginDTO loginDTO) {
        return CommonResult.success(authorizeService.login(loginDTO));
    }

    @Operation(summary = "登出", description = "注销当前用户会话，通常会使令牌失效。")
    @PostMapping("/logout")
    public CommonResult logout(@CurrentSecurityContext(expression = Constant.AUTHENTICATION) Authentication authentication) {
        MyUserDetails principal = (MyUserDetails) authentication.getPrincipal();
        return CommonResult.success(authorizeService.logout(principal));
    }

    @Operation(summary = "刷新令牌", description = "刷新授权令牌，通常是提供一个旧的令牌以获取一个新的令牌。")
    @PostMapping("/refreshToken")
    public CommonResult refreshToken(HttpServletRequest request) {
        return CommonResult.success(authorizeService.refreshToken(request));
    }

    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的信息。")
    @GetMapping("/me")
    public CommonResult getCurrentUser() {
        return CommonResult.success("");
    }
}
